<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>canvas-demos</title>

    <style>
        canvas {
            margin: 0 auto;
            border: 2px solid #aaa;
            display: block;
        }
    </style>
</head>

<body>
<canvas id="cont" width="500px" height="500px">浏览器不支持</canvas>
<!--只能使用原生的js,如果让canvas左右居中使用display:block-->
<script>
    // 固定start获取画布
    const canvas = document.querySelector('#cont')
    // 获取画布上下文
    const ctx = canvas.getContext('2d')
    // 固定end

    const w = h = 500

    /**
     * 获取随机值
     * @param inputNumber
     */
    function randomNum(inputNumber) {
        return Math.random() * inputNumber
    }

    function Ball() {
        this.x = randomNum(5) + 60
        this.y = randomNum(3) + 60
        this.r = randomNum(50) + 10
        this.color = '#' + parseInt((Math.random() * 0xFFFFFF).toString()).toString(16)
        this.xSpeed = randomNum(3) + 2
        this.ySpeed = randomNum(3) + 1
    }

    // 定义小球显示方法
    Ball.prototype.show = function () {
        this.run()
        ctx.beginPath()
        ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2)
        ctx.fillStyle = this.color
        ctx.fill()
    }
    // 定义小球运动方法
    Ball.prototype.run = function () {
        if (this.x - this.r <= 0 || this.x + this.r >= w) {
            this.xSpeed = -this.xSpeed
        }
        this.x += this.xSpeed
        // 水平运动

        if (this.y - this.r <= 0 || this.y + this.r >= h) {
            this.ySpeed = -this.ySpeed
        }
        this.y += this.ySpeed
    }

    // 创建小球的数组
    const ballArr = []
    for (let i = 0; i < 100; i++) {
        const ball = new Ball();
        ballArr.push(ball)
        ball.show()
    }
    // 小球运动
    setInterval(function () {
        // 清除画布
        ctx.clearRect(0, 0, w, h)
        for (const ballArrElement of ballArr) {
            ballArrElement.show()
        }
    }, 10)
</script>
</body>
</html>
